from flask import Flask, request, jsonify
import os
from datetime import datetime
from data_loader import UDMDataLoader

app = Flask(__name__)

# Initialize data loader
data_loader = UDMDataLoader()

@app.route('/service/user/UdmSubscription', methods=['GET'])
def udm_subscription():
    """UDM Subscription API endpoint"""
    msisdn = request.args.get('number')
    
    if not msisdn:
        return jsonify({
            "code": 400,
            "message": "Missing required parameter: number",
            "result": None
        }), 400
    
    # Get demo data for the MSISDN
    demo_data = data_loader.get_msisdn_data(msisdn)
    
    # Construct the response in the same format as the sample
    response = {
        "code": 200,
        "message": "操作成功",
        "result": {
            "records": [demo_data],
            "total": 1,
            "size": 10,
            "current": 1,
            "orders": [],
            "optimizeCountSql": True,
            "hitCount": False,
            "countId": None,
            "maxLimit": None,
            "searchCount": True,
            "pages": 1
        }
    }
    
    return jsonify(response)

@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({
        "status": "healthy",
        "service": "UDM API Server Demo",
        "timestamp": datetime.now().isoformat()
    })

@app.route('/', methods=['GET'])
def root():
    """Root endpoint with API information"""
    return jsonify({
        "service": "UDM API Server Demo",
        "version": "1.0.0",
        "endpoints": {
            "udm_subscription": "/service/user/UdmSubscription?number=<msisdn>",
            "health": "/health"
        },
        "sample_msisdns": data_loader.get_available_msisdns()
    })

@app.route('/msisdns', methods=['GET'])
def list_msisdns():
    """List all available MSISDNs"""
    return jsonify({
        "available_msisdns": data_loader.get_available_msisdns(),
        "total_count": len(data_loader.get_available_msisdns())
    })

if __name__ == '__main__':
    port = int(os.environ.get('PORT', 81))
    app.run(host='0.0.0.0', port=port, debug=True) 